# LTGSQL Database Makefile

# 平台检测
ifeq ($(OS),Windows_NT)
    PLATFORM = windows
    CC = gcc
    CFLAGS = -std=c23 -Wall -Wextra -O2 -g
    LDFLAGS =
    SRC_EXTRA = src/utils/input_win.c
else
    PLATFORM = unix
    CC = gcc
    CFLAGS = -std=c23 -Wall -Wextra -O2 -g
    LDFLAGS = -lpthread -lm -lrt
    SRC_EXTRA = src/utils/input_unix.c
endif

# 如果是 MinGW 环境，可能需要额外的链接库
ifneq (,$(findstring MINGW,$(shell uname -s)))
    LDFLAGS += -lreadline
endif

# 目录设置
SRC_DIR = src
BUILD_DIR = build
BIN_DIR = bin
TEST_DIR = tests
INCLUDE_DIR = src/include

# 源文件查找
CORE_SRCS = $(wildcard $(SRC_DIR)/core/*.c) \
             $(wildcard $(SRC_DIR)/core/*/*.c)
NETWORK_SRCS = $(wildcard $(SRC_DIR)/network/*.c)
UTILS_SRCS = $(wildcard $(SRC_DIR)/utils/*.c)
MAIN_SRC = $(SRC_DIR)/main.c

# 目标文件
OBJS = $(CORE_SRCS:$(SRC_DIR)/%.c=$(BUILD_DIR)/%.o) \
       $(NETWORK_SRCS:$(SRC_DIR)/%.c=$(BUILD_DIR)/%.o) \
       $(UTILS_SRCS:$(SRC_DIR)/%.c=$(BUILD_DIR)/%.o)

# 主目标
TARGET = $(BIN_DIR)/ltgsql




# Windows 特殊处理
ifeq ($(PLATFORM),windows)
    CFLAGS += -DLTGSQL_WINDOWS=1
else
    CFLAGS += -DHAVE_READLINE=1
endif

$(TARGET): $(OBJS) build/main.o
	@mkdir -p $(dir $@)
	$(CC) $(OBJS) build/main.o -o $@ $(LDFLAGS)


# 默认目标
all: $(TARGET)

# 链接主程序
$(TARGET): $(OBJS) $(BUILD_DIR)/main.o
	@mkdir -p $(BIN_DIR)
	$(CC) $(OBJS) $(BUILD_DIR)/main.o -o $@ $(LDFLAGS)
	@echo "LTGSQL built successfully: $(TARGET)"

# 编译规则
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -I$(INCLUDE_DIR) -c $< -o $@

# 测试目标
test: $(TARGET)
	@echo "Running tests..."
	$(MAKE) -C $(TEST_DIR)

# 性能测试
benchmark: $(TARGET)
	@echo "Running benchmarks..."
	$(MAKE) -C benchmarks

# 清理
clean:
	rm -rf $(BUILD_DIR) $(BIN_DIR)
	@echo "Clean complete"

# 安装
install: $(TARGET)
	cp $(TARGET) /usr/local/bin/ltgsql
	@echo "LTGSQL installed to /usr/local/bin/ltgsql"

# 格式化代码
format:
	find $(SRC_DIR) -name "*.c" -o -name "*.h" | xargs clang-format -i
	@echo "Code formatting complete"

.PHONY: all clean test benchmark install format